"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { BarChart3, User, Lock, Mail, Eye, EyeOff, UserPlus } from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import { api, useApiCall } from "@/lib/api"
import { RegisterRequest } from "@/lib/types/api"
import { withGuest } from "@/components/auth-guard"

function RegisterPage() {
  const [formData, setFormData] = useState({
    username: "",
    email: "",
    password: "",
    confirmPassword: "",
    trueName: "",
    phone: ""
  })
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const router = useRouter()
  const { toast } = useToast()

  const { execute: registerUser, isLoading: isRegistering } = useApiCall(
    api.auth.register,
    {
      showToast: true,
    }
  )

  const handleInputChange = (field: keyof typeof formData) => (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData(prev => ({
      ...prev,
      [field]: e.target.value
    }))
  }

  const validateForm = (): string | null => {
    if (!formData.username.trim()) {
      return "请输入用户名"
    }
    if (formData.username.length < 3) {
      return "用户名至少需要3个字符"
    }
    if (!formData.email.trim()) {
      return "请输入邮箱地址"
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      return "请输入有效的邮箱地址"
    }
    if (!formData.password) {
      return "请输入密码"
    }
    if (formData.password.length < 6) {
      return "密码至少需要6个字符"
    }
    if (formData.password !== formData.confirmPassword) {
      return "两次输入的密码不一致"
    }
    return null
  }

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault()
    
    const validationError = validateForm()
    if (validationError) {
      toast({
        title: "注册失败",
        description: validationError,
        variant: "destructive",
        duration: 3000,
      })
      return
    }

    const registerRequest: RegisterRequest = {
      username: formData.username.trim(),
      email: formData.email.trim(),
      password: formData.password,
      confirmPassword: formData.confirmPassword,
      trueName: formData.trueName.trim() || undefined,
      phone: formData.phone.trim() || undefined,
    }

    const result = await registerUser(registerRequest)
    
    // 注册成功的处理
    if (result) {
      toast({
        title: "注册成功",
        description: "账号创建成功，请登录使用系统",
        duration: 3000,
      })
      // 注册成功后跳转到登录页
      router.push('/login')
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-background via-background to-muted/20 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* Logo和标题 */}
        <div className="text-center mb-8">
          <div className="flex justify-center mb-6">
            <div className="flex items-center justify-center w-20 h-20 rounded-full bg-accent/10 border-2 border-accent/20">
              <BarChart3 className="w-10 h-10 text-accent" />
            </div>
          </div>
          <h1 className="text-3xl font-bold text-foreground bg-gradient-to-r from-foreground to-accent bg-clip-text text-transparent">
            股票AI智能分析系统
          </h1>
          <p className="text-muted-foreground mt-3 text-base">创建账号，开始您的投资分析之旅</p>
        </div>

        {/* 注册卡片 */}
        <Card className="shadow-xl border-accent/20 backdrop-blur-sm bg-card/95">
          <CardHeader className="space-y-3 pb-6">
            <CardTitle className="text-2xl text-center font-bold">用户注册</CardTitle>
            <p className="text-sm text-muted-foreground text-center">
              填写信息创建您的专属账号
            </p>
          </CardHeader>
          <CardContent className="pb-6">
            <form onSubmit={handleRegister} className="space-y-4">
              {/* 用户名输入 */}
              <div className="space-y-2">
                <label htmlFor="username" className="text-sm font-medium text-foreground">
                  用户名 <span className="text-destructive">*</span>
                </label>
                <div className="relative group">
                  <User className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground group-focus-within:text-accent transition-colors" />
                  <Input
                    id="username"
                    type="text"
                    placeholder="请输入用户名 (至少3个字符)"
                    value={formData.username}
                    onChange={handleInputChange('username')}
                    className="pl-10 h-11 bg-background/50 border-muted-foreground/20 focus:border-accent focus:ring-accent/20 transition-all"
                    disabled={isRegistering}
                    required
                  />
                </div>
              </div>

              {/* 真实姓名输入 */}
              <div className="space-y-2">
                <label htmlFor="trueName" className="text-sm font-medium text-foreground">
                  真实姓名 <span className="text-muted-foreground text-xs">(可选)</span>
                </label>
                <div className="relative group">
                  <User className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground group-focus-within:text-accent transition-colors" />
                  <Input
                    id="trueName"
                    type="text"
                    placeholder="请输入真实姓名"
                    value={formData.trueName}
                    onChange={handleInputChange('trueName')}
                    className="pl-10 h-11 bg-background/50 border-muted-foreground/20 focus:border-accent focus:ring-accent/20 transition-all"
                    disabled={isRegistering}
                  />
                </div>
              </div>

              {/* 手机号输入 */}
              <div className="space-y-2">
                <label htmlFor="phone" className="text-sm font-medium text-foreground">
                  手机号 <span className="text-muted-foreground text-xs">(可选)</span>
                </label>
                <div className="relative group">
                  <User className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground group-focus-within:text-accent transition-colors" />
                  <Input
                    id="phone"
                    type="tel"
                    placeholder="请输入手机号"
                    value={formData.phone}
                    onChange={handleInputChange('phone')}
                    className="pl-10 h-11 bg-background/50 border-muted-foreground/20 focus:border-accent focus:ring-accent/20 transition-all"
                    disabled={isRegistering}
                  />
                </div>
              </div>

              {/* 邮箱输入 */}
              <div className="space-y-2">
                <label htmlFor="email" className="text-sm font-medium text-foreground">
                  邮箱 <span className="text-destructive">*</span>
                </label>
                <div className="relative group">
                  <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground group-focus-within:text-accent transition-colors" />
                  <Input
                    id="email"
                    type="email"
                    placeholder="请输入邮箱地址"
                    value={formData.email}
                    onChange={handleInputChange('email')}
                    className="pl-10 h-11 bg-background/50 border-muted-foreground/20 focus:border-accent focus:ring-accent/20 transition-all"
                    disabled={isRegistering}
                  />
                </div>
              </div>

              {/* 密码输入 */}
              <div className="space-y-2">
                <label htmlFor="password" className="text-sm font-medium text-foreground">
                  密码 <span className="text-destructive">*</span>
                </label>
                <div className="relative group">
                  <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground group-focus-within:text-accent transition-colors" />
                  <Input
                    id="password"
                    type={showPassword ? "text" : "password"}
                    placeholder="请输入密码 (至少6个字符)"
                    value={formData.password}
                    onChange={handleInputChange('password')}
                    className="pl-10 pr-10 h-11 bg-background/50 border-muted-foreground/20 focus:border-accent focus:ring-accent/20 transition-all"
                    disabled={isRegistering}
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-muted-foreground hover:text-accent transition-colors"
                    disabled={isRegistering}
                  >
                    {showPassword ? (
                      <EyeOff className="w-4 h-4" />
                    ) : (
                      <Eye className="w-4 h-4" />
                    )}
                  </button>
                </div>
              </div>

              {/* 确认密码输入 */}
              <div className="space-y-2">
                <label htmlFor="confirmPassword" className="text-sm font-medium text-foreground">
                  确认密码 <span className="text-destructive">*</span>
                </label>
                <div className="relative group">
                  <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground group-focus-within:text-accent transition-colors" />
                  <Input
                    id="confirmPassword"
                    type={showConfirmPassword ? "text" : "password"}
                    placeholder="请再次输入密码"
                    value={formData.confirmPassword}
                    onChange={handleInputChange('confirmPassword')}
                    className="pl-10 pr-10 h-11 bg-background/50 border-muted-foreground/20 focus:border-accent focus:ring-accent/20 transition-all"
                    disabled={isRegistering}
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-muted-foreground hover:text-accent transition-colors"
                    disabled={isRegistering}
                  >
                    {showConfirmPassword ? (
                      <EyeOff className="w-4 h-4" />
                    ) : (
                      <Eye className="w-4 h-4" />
                    )}
                  </button>
                </div>
              </div>

              {/* 注册按钮 */}
              <div className="pt-4">
                <Button 
                  type="submit" 
                  className="w-full h-11 bg-accent hover:bg-accent/90 text-accent-foreground font-medium shadow-lg hover:shadow-xl transition-all duration-200" 
                  disabled={isRegistering}
                >
                  {isRegistering ? (
                    <>
                      <UserPlus className="w-4 h-4 mr-2 animate-spin" />
                      注册中...
                    </>
                  ) : (
                    <>
                      <UserPlus className="w-4 h-4 mr-2" />
                      创建账号
                    </>
                  )}
                </Button>
              </div>
            </form>

            {/* 登录链接 */}
            <div className="mt-6 text-center">
              <p className="text-sm text-muted-foreground">
                已有账号？
                <Link 
                  href="/login" 
                  className="text-accent hover:text-accent/80 hover:underline ml-1 font-medium"
                >
                  立即登录
                </Link>
              </p>
            </div>
          </CardContent>
        </Card>

        {/* 页脚信息 */}
        <div className="mt-8 text-center">
          <div className="space-y-2 text-xs text-muted-foreground/80">
            <p className="font-medium">股票AI智能分析系统 v1.0</p>
            <p>专业的股票推荐分析和监控平台</p>
            <div className="flex items-center justify-center space-x-4 mt-3 pt-3 border-t border-muted-foreground/10">
              <span>© 2024</span>
              <span className="w-1 h-1 bg-muted-foreground/40 rounded-full"></span>
              <span>安全注册</span>
              <span className="w-1 h-1 bg-muted-foreground/40 rounded-full"></span>
              <span>数据加密</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default withGuest(RegisterPage)